package seatiger.tomcat.catalina.core;

import seatiger.tomcat.catalina.Context;
import seatiger.tomcat.catalina.deploy.FilterDef;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Enumeration;
import java.util.Optional;

/**
 * Filter 的配置
 */
public class ApplicationFilterConfig implements FilterConfig {

    /**
     * 关联的容器对象
     */
    private Context context;

    /**
     * 实例
     */
    private Filter filter;

    /**
     * filter的定义
     */
    private FilterDef filterDef;


    public ApplicationFilterConfig(Context context, FilterDef filterDef)
            throws ClassCastException, ClassNotFoundException,
            IllegalAccessException, InstantiationException,
            ServletException {
        this.context = context;
        setFilterDef(filterDef);
    }

    private void setFilterDef(FilterDef filterDef)
            throws ClassCastException, ClassNotFoundException,
            IllegalAccessException, InstantiationException,
            ServletException {
        this.filterDef = filterDef;
        if (filterDef == null){
            Optional.ofNullable(filter).ifPresent(f -> {
                f.destroy();
                this.filter = null;
            });
        }else {
            //实例化Filter，并执行Filter.init方法
            getFilter();
        }
    }

    /**
     * 获取Filter ,实例化之后，并执行init方法
     * @return
     * @throws ClassCastException
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws ServletException
     */
    public Filter getFilter() throws ClassCastException, ClassNotFoundException,
            IllegalAccessException, InstantiationException, ServletException {
        if (filter != null){
            return filter;
        }
        String filterClass = filterDef.getFilterClass();
        ClassLoader classLoader = null;
        //如果是内部的过滤器，就使用当前的类加载器
        if (filterClass.startsWith("seatiger.tomcat.catalina.")){
            classLoader = this.getClass().getClassLoader();
        }else {
            //获取自定义类加载器
            classLoader = context.getLoader().getClassLoader();
        }
        Class<?> aClass = classLoader.loadClass(filterClass);
        this.filter = (Filter)aClass.newInstance();
        filter.init(this);
        return filter;
    }


    @Override
    public String getFilterName() {
        return filterDef.getFilterName();
    }

    @Override
    public ServletContext getServletContext() {
        return context.getServletContext();
    }

    @Override
    public String getInitParameter(String s) {
        return null;
    }

    @Override
    public Enumeration getInitParameterNames() {
        return null;
    }

    public void release() {
        Optional.ofNullable(filter).ifPresent(f -> f.destroy());
    }
}
